package com.joker.demo.admin.domain.po;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 执行器组实体类
 *
 * @author feixiang.li
 * @since 2025/7/23
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_job_group")
public class JobGroupPO extends BaseEntity {

    /**
     * 执行器组名称-groupName (应用名称)
     */
    private String groupName;

    /**
     * 执行器名称-jobName
     */
    private String jobName;

    /**
     * groupName + jobName 组合唯一标识
     */
    private String groupJobName;

    /**
     * 地址类型:0=自动注册,1=手动录入
     */
    private Integer addressType;

    /**
     * 执行器地址列表,用逗号去除
     * 格式ip:port,ip:port
     */
    private String addressList;

    /**
     * 执行器地址列表
     */
    @TableField(exist = false)
    private List<String> clientIdList;

    public JobGroupPO() {
        clientIdList = new ArrayList<>();
    }


    /**
     * 设置执行器地址列表
     *
     * @param addressList 执行器地址列表
     */
    public void setAddressList(String addressList) {
        this.addressList = addressList;
        if (StringUtils.isNotBlank(addressList)) {
            this.clientIdList = new ArrayList<>(Arrays.asList(addressList.split(",")));
        } else {
            this.clientIdList = new ArrayList<>();
        }
    }


    /**
     * 格式为ip:port
     *
     * @param address 需要加入的ip:port 地址
     */
    public void addAddressList(String address) {
        if (StringUtils.isBlank(address) || clientIdList.contains(address)) {
            return;
        }
        this.clientIdList.add(address);
        addressList = StringUtils.join(clientIdList, ",");
    }


    /**
     * 格式为ip:port。删除
     *
     * @param address 需要删除的ip:port 地址
     * @return 表示当前jobHandler还剩余多少个地址
     */
    public Integer removeAddressList(String address) {
        if (StringUtils.isBlank(address)) {
            return CollUtil.size(clientIdList);
        }
        if (clientIdList == null) {
            clientIdList = new ArrayList<>();
        }
        this.clientIdList.remove(address);
        addressList = StringUtils.join(clientIdList, ",");
        return CollUtil.size(clientIdList);
    }
} 